if select(2, UnitClass('player')) ~= "SHAMAN" then
	return
end
local L = LibStub("AceLocale-3.0"):GetLocale("Yata")
local Yata_ScanningTooltip
local Yata_SpellBlacklist = {GetSpellInfo(36936)} -- Totemic Call
local Yata_TotemTiming = {L["(%d+) min cooldown"], L["(%d+) sec cooldown"]}
local Yata_ToolsTotemRegex = L["Tools_totem_regex"]
function Yata:InitTotems()
	Yata_ScanningTooltip = CreateFrame( "GameTooltip", "YataScanningTooltip" ) -- Tooltip name cannot be nil
	Yata_ScanningTooltip:SetOwner( WorldFrame, "ANCHOR_NONE" )
	Yata_ScanningTooltip:AddFontStrings( Yata_ScanningTooltip:CreateFontString( "$parentTextLeft1", nil, "GameTooltipText" ), Yata_ScanningTooltip:CreateFontString( "$parentTextRight1", nil, "GameTooltipText" ) )
	self:GatherTotemData()
	if(#self.TotemData == 0) then 
		self:Print("No totems found, level too low?")
		return false
	end
	return true
end

function Yata:GetTotem(name)
	local result = nil
	for k,v in ipairs(Yata.TotemData) do
		local totem = Yata.TotemData[v]
		totem = totem[#totem]
		if totem.Name == name then		
			result = totem
			break
		end
	end
	return result
end

-----------------------------
-- Utility functions below --
-----------------------------

function Yata:ReverseTranslation(value)
	local result = nil
	for k,v in pairs(L) do
		if v == value then
			result = k
			break
		end
	end	
	return result
end


function Yata:GetTooltip(totem)	
	Yata_ScanningTooltip:ClearLines()
	Yata_ScanningTooltip:SetSpell( totem.SpellID, "spell" )
	local tooltip = {}
	for i=1,Yata_ScanningTooltip:NumLines() do
	   local myRightText = getglobal("YataScanningTooltipTextRight" .. i)
	   local myLeftText = getglobal("YataScanningTooltipTextLeft" .. i)
	   local line = {left = "", right = ""}
	   line.right = myRightText:GetText() or ""
	   line.left = myLeftText:GetText() or ""
	   table.insert(tooltip,line)
	end	
	return tooltip
end

function Yata:SpellBlacklist(spell)
	local blacklist = nil
	for k,v in ipairs(Yata_SpellBlacklist) do
		if(spell == v) then
			blacklist = true
			break
		end
	end
	return blacklist
end


function Yata:GatherTotemData()
    self.TotemData = {}
    local tabs = GetNumSpellTabs()
    for tab = 2, tabs do
	local _, _, offset, numSpells = GetSpellTabInfo(tab)
	for i = 1, numSpells do
	    local spell = offset + i
	    local SpellName, subspell = GetSpellName(spell, "spell")
	    if (string.find(string.lower(SpellName), string.lower("Totem")) and not self:SpellBlacklist(SpellName)) then

		if (not self.TotemData[SpellName]) then
		    self.TotemData[SpellName] = {}
		    table.insert(self.TotemData, SpellName)
		end
		local totem = {}
		totem.SpellID = spell
		totem.Name = SpellName
		table.insert(self.TotemData[SpellName],totem)
	    end
	end
    end
    local count = 0
    -- Add Spell Information (Cooldown,Duration, HP, Element)    	
    	for k,v in ipairs(self.TotemData) do
    		for l,w in ipairs(self.TotemData[v]) do
			self:ExtractToolTip(w)
		end
		count = count + 1
	end
    self.TotemData.Count = count
end

--- Return Cooldown, Duration, HP, Element
--- Not yet fully converted to Gratuity/Deformat
function Yata:ExtractToolTip(totem)
	local tooltip = self:GetTooltip(totem)
	local element = ""
	totem.Element = ""
	totem.Cooldown = 0
	totem.Health = 0
	totem.Duration = 0
	totem.Mana = 0
	-- SpellTexture --
	totem.Texture = GetSpellTexture(totem.SpellID,"spell")	
	-- Mana cost --
	local totemmana = string.gsub(MANA_COST,"(%%d)","(%%d+)")
	totem.Mana = string.match(tooltip[2].left..tooltip[2].right, totemmana)
	-- Element extraction --	
	local element = string.match(tooltip[4].left..tooltip[4].right, Yata_ToolsTotemRegex)
	if( element ) then	
		if( string.sub( element, 1, 1 ) == "|" ) then
			element = string.sub( element, 11 )
		end
		_, _, element = string.find(element, "(%a*)")
		-- localization hacks incoming --
		if( GetLocale() == "deDE" ) then
			if(element == "Erd") then
				element = "Erde" -- "Werkzeuge: Erdtotem", rename Erd to Erde
			end
		end
		totem.Element = self:ReverseTranslation(element) -- not integrated in AceLocale-3.0 anymore
	end
	-- End Element --
	-- Start Cooldown -- 
	local matches = {}
	text = tooltip[3].left..tooltip[3].right
	if(text) then
	    for num, regex in ipairs(Yata_TotemTiming) do
		     for k in string.gmatch(text,regex) do
	       		if(num == 1) then
	       			table.insert(matches,tonumber(k*60))
	       		else
					table.insert(matches,tonumber(k))
	       		end
		     end
	    end
	    table.sort(matches)
	    if matches[#matches] then
			totem.Cooldown = matches[#matches]
		end
	end
	-- End Cooldown --
end
function Yata:OutputTotemData()
	for k,v in ipairs(self.TotemData) do
		for l,w in ipairs(self.TotemData[v]) do
			local output = string.format("%s Rank %i, HP: %s, Duration: %i, Element: %s, Cooldown: %i, Mana: %i", v,l,w.Health, w.Duration, w.Element, w.Cooldown, w.Mana)
			DEFAULT_CHAT_FRAME:AddMessage(output)
		end
	end
end
